import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:laos_mall/app_route.dart';
import 'package:laos_mall/common/base/base_controller.dart';
import 'package:laos_mall/common/base/page_size_controller.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/utils/widget_util.dart';
import 'package:laos_mall/common/widght/image_widget.dart';
import 'package:laos_mall/common/widght/item_widget.dart';
import 'package:laos_mall/common/widght/mall/zb_Item_widget.dart';
import 'package:laos_mall/common/widght/toast/showtoast.dart';
import 'package:laos_mall/models/category/para_product.dart';
import 'package:laos_mall/models/category/product_list_model.dart';
import 'package:laos_mall/models/home/home_model.dart';
import 'package:laos_mall/pages/main/config.dart';
import 'package:laos_mall/pages/main/widgets/product_item_logic.dart';
import 'package:laos_mall/pages/point_mall/point_detail/view.dart';
import 'package:skeletonizer/skeletonizer.dart';

import '../catergory/sku/view.dart';

class ProductItemWidget extends StatefulWidget {
  ProductItemWidget(
      {super.key, this.name, this.physics, this.title, this.topSpace = 15,this.para,this.autoPage = true});

  final String? name;
  ScrollPhysics? physics;
  final String? title;
  double topSpace;
  final ParamProduct? para;
  final bool autoPage; //是否自动翻页
  @override
  State<ProductItemWidget> createState() => _ProductItemWidgetState();
}


class _ProductItemWidgetState extends State<ProductItemWidget> {
  late ProductItemLogic logic;
  @override
  void initState() {
    final ProductItemLogic logic = Get.put(
        ProductItemLogic(param: widget.para ?? ParamProduct(cat: widget.name),tag: widget.name), tag: widget.name);
    this.logic = logic;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    bool isLargeScreen = MediaQuery
        .of(context)
        .size
        .width > 600;

    return GetBuilder<ProductItemLogic>(builder: (logic) {
      Widget child = Obx(() {
        if (logic.netState == NetworkState.success) {
           return _buildWidget();
        }
        return _buildWidgetSkeleton();
      });

      if (widget.physics == null) {
        child = child.addExpand();
      }
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.title ?? "may_like".tr,
            style: AppStyle.textStyleLight,
          )
              .addPadding(EdgeInsets.only(left: 15, top: widget.topSpace))
              .addVisibility(widget.title != null),
          child
        ],
      );
    }, tag: widget.name,);
  }

  Widget _buildWidget() {
    bool isLargeScreen = MediaQuery
        .of(context)
        .size
        .width > 600;

    var items = logic.dataSource;
   return  PageSizeGridView(itemBuilder: (context, index,data) {
      var item = logic.dataSource[index];
      return Stack(
        fit: StackFit.expand,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ImageWidget(
                url: item.pic_url,
                fit: BoxFit.fill,
              ).addContainer(height: 156.w,width: 156.w),
              const Spacer(),
              Text(
                item.product_name,
                style: AppStyle.subtitleLightStyle,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              ItemWidget(
                prefixItem: "${Config.symbol}${item.product_price}",
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                suffixItem: Image.asset(
                  (item.is_collect == true ? "ic_heart_fill" : 'ic_heart_black').toImgPath(),
                  width: 13.w,
                  height: 13.w,
                )
                    .addContainer(
                    height: 25.w,
                    width: 25.h,
                    alignment: Alignment.centerRight,
                    color: Colors.transparent)
                    .addGestureTap(() {
                  logic.collectProduct(index,item);
                }),
                titleStyle: AppStyle.textStyle,
              )
            ],
          ),
          Positioned(
              right: 10.w,
              top: 120.w,
              width: 26.w,
              height: 26.w,
              child: Image.asset(
                'ic_cart_big'.toImgPath(),
                fit: BoxFit.contain,
              )
                  .addContainer(
                  width: 26.w,
                  height: 26.w,
                  radius: 13.w,
                  color: Colors.white,
                  padding: EdgeInsets.all(6.w))
                  .addGestureTap(() {
                // Get.toNamed(AppRouter.sku,);
                // Get.bottomSheet(SkuPage(skuId: item.product_sku.firstOrNull?.sku_id,productId:   item.product_id));
                logic.addCart(item);
              }))
        ],
      ).addGestureTap(() {
        Get.toNamed(AppRouter.productDetail,arguments: {"id":item.product_id});
      });
    }, controller: logic,gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: isLargeScreen ? 200.w : 156.w,
        childAspectRatio: isLargeScreen ? 200.0 / 250.0 : 156.0 / (196.0),
        mainAxisSpacing: isLargeScreen ? 20.w : 15.w,
        crossAxisSpacing: isLargeScreen ? 30.w : 22.w),physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),padding: EdgeInsets.symmetric(horizontal: 15)).addPadding(EdgeInsets.only(top: 12.h));
  }

  Widget _buildWidgetSkeleton() {
    bool isLargeScreen = MediaQuery
        .of(context)
        .size
        .width > 600;
    return GridView.builder(
      shrinkWrap: true,
      physics: widget.physics ?? const AlwaysScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(horizontal: 15),
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: isLargeScreen ? 200.w : 156.w,
          childAspectRatio: isLargeScreen ? 200.0 / 250.0 : 156.0 / (196.0),
          mainAxisSpacing: isLargeScreen ? 20.w : 15.w,
          crossAxisSpacing: isLargeScreen ? 30.w : 22.w),
      itemBuilder: (context, index) {
        return Stack(
          fit: StackFit.expand,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: double.infinity, height: 156.w, color: Colors.white,)
                    .addSkeleton(),
                const Spacer(),
                Text(
                  "Mid-waist Flared Jeans",
                  style: AppStyle.subtitleLightStyle,
                ).addContainer().addSkeleton(),
                const Spacer(),
                ItemWidget(
                  prefixItem: "\$999.99",
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  suffixItem: Icon(Icons.ac_unit, size: 20),
                  titleStyle: AppStyle.textStyle,
                ).addContainer().addSkeleton()
              ],
            ),
            // Positioned(
            //     right: 10.w,
            //     top: 120.w,
            //     width: 26.w,
            //     height: 26.w,
            //     child: Container(
            //         width: 26.w,
            //         height: 26.w,
            //         color: Colors.white,
            //         padding: EdgeInsets.all(6.w)))
          ],
        );
      },
      itemCount: 6,
    ).addPadding(EdgeInsets.only(top: 12.h));
  }
}

class PointListView extends StatelessWidget {
  final List<String> items = List.generate(30, (index) => '$index');

  PointListView({super.key});

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      itemCount: (items.length / 2).ceil(), // 每行显示 3 个 item
      itemBuilder: (context, rowIndex) {
        final startIndex = rowIndex * 2;
        final endIndex = (rowIndex + 1) * 2;
        final rowItems = items.sublist(
          startIndex,
          endIndex < items.length ? endIndex : items.length,
        );

        return Wrap(
          spacing: 20.w, // 水平间距
          runSpacing: 8.0, // 垂直间距
          children: rowItems.map((item) {
            return _buildPointItem();
          }).toList(),
        );
      },
    );
  }

  Widget _buildPointItem() {
    return Stack(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Image.asset(
              'img1.jpeg'.toImgPath(directory: 'test_img'),
              fit: BoxFit.cover,
            ).addContainer(height: 156.w),
            Text(
              "Mid-waist Flared 124124124124214124214214214fqwrqqrqwrw2",
              style: AppStyle.subtitleLightStyle,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            )
                .addContainer(color: Colors.transparent)
                .addPadding(EdgeInsets.only(top: 6.h)),
            Row(
              children: [
                Text(
                  "${Config.symbol}400",
                  style: AppStyle.subtitleLightStyleGray
                      .copyWith(decoration: TextDecoration.lineThrough),
                ),
                Spacer(),
                ItemWidget(
                  prefixItem: Image.asset(
                    'ic_sanbin'.toImgPath(),
                    width: 11.w,
                    height: 11.w,
                  ),
                  suffixItem: "999",
                  space: 4,
                )
              ],
            ).addPadding(EdgeInsets.only(bottom: 20.h, top: 10.h))
          ],
        ),
        Positioned(
            right: 10.w,
            top: 120.w,
            width: 26.w,
            height: 26.w,
            child: Image.asset(
              'ic_cart_big'.toImgPath(),
              fit: BoxFit.contain,
            )
                .addContainer(
                width: 26.w,
                height: 26.w,
                radius: 13.w,
                color: Colors.white,
                padding: EdgeInsets.all(6.w))
                .addGestureTap(() {
              showToast("加入购物车", value: 1);

            }))
      ],
    )
        .addContainer(
      width: (ScreenUtil().screenWidth - 61.w) / 2.0,
    )
        .addGestureTap(() {
      // Get.toNamed(AppRouter.productDetail);
      Get.to(() => PointDetailPage());
    });
  }
}
